import { useMutation, useQuery, useQueryClient } from '@umijs/max';
import { notification } from 'antd';
import { request } from '../axios';
import APP_PRE from '../constant';
import QUERY_KEYS from '../constant';

const prefix = `${APP_PRE.APP_NAME}/comment`;

const useGetAllCommentByAid = (articleId: number, accountId: number) => {
  return useQuery(
    [QUERY_KEYS.COMMENT_GET_ALL_BY_AID, articleId, accountId],
    () =>
      request<API.IResult<CommentType[]>>(`${prefix}/getAllByAid`, {
        method: 'GET',
        params: {
          articleId,
          accountId,
        },
      }),
  );
};

const useGetTopComment = () => {
  return useQuery([QUERY_KEYS.COMMENT_GET_ALL_BY_AID], () =>
    request<API.IResult<(CommentType & API.IArticles)[]>>(
      `${prefix}/public/getTop`,
    ),
  );
};

const useAddComment = () => {
  const queryClient = useQueryClient();
  return useMutation(
    (comment: API.IComment) =>
      request<API.IResult<API.IInsertId>>(`${prefix}/add`, {
        method: 'POST',
        data: comment,
      }),
    {
      onSuccess: (res: API.IResult<API.IInsertId>) => {
        if (res.code === 200) {
          notification.success({
            message: '评论成功',
          });
          queryClient.invalidateQueries([QUERY_KEYS.COMMENT_GET_ALL_BY_AID]);
        }
      },
    },
  );
};

export { useGetAllCommentByAid, useAddComment, useGetTopComment };
